import { getCar, updateCar, delCar } from '@/api/car'
export default {
  namespaced: true,
  state () {
    return {
      carList: []
    }
  },
  mutations: {
    setCar (state, newList) {
      state.carList = newList
    },
    changeCheck (state, goodsid) {
      const good = state.carList.find(item => item.goods_id === goodsid)
      good.isChecked = !good.isChecked
    },
    changeAll (state, flag) {
      state.carList.forEach(item => {
        item.isChecked = flag
      })
    },
    changeCount (state, { value, goodsId }) {
      const obj = state.carList.find(item => item.goods_id === goodsId)
      // console.log(goodsId)
      obj.goods_num = value
    }
  },
  actions: {
    async getCarAction (context) {
      const { data } = await getCar()
      // 回台返回数据不包括是否选中，自行添加
      // console.log(data)
      data.list.forEach(item => {
        item.isChecked = true
      })
      context.commit('setCar', data.list)
    },
    async changeCountAction (context, obj) {
      const { goodsId, value, goodsSkuId } = obj
      // console.log(obj)
      context.commit('changeCount', {
        goodsId,
        value
      })
      await updateCar(goodsId, value, goodsSkuId)
    },
    async delCarAction (context) {
      const obj = context.getters.selCarList
      // console.log(obj)
      const Ids = obj.map(item => item.id)
      // console.log(Ids)
      await delCar(Ids)

      // 重新渲染
      await context.dispatch('getCarAction')
    }
  },
  getters: {
    carTotal (state) {
      return state.carList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    selCarList (state) {
      return state.carList.filter(item => item.isChecked)
    },
    selCount (state, getters) {
      return getters.selCarList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    selPrice (state, getters) {
      return getters.selCarList.reduce((sum, item) => sum + item.goods_num * item.goods.goods_price_min, 0)
    },
    isAllChecked (state) {
      return state.carList.every(item => item.isChecked)
    }
  }
}
